import { createRouter, createWebHashHistory } from "vue-router";
import store from "../store";
import { ElMessage } from 'element-plus';

const routes = [
    {
        path:'/',
        redirct:'/',
        name:'index',
        component:()=>import('../view/index.vue'),
    },
    {
        path:'/backindex',
        name:'backindex',
        component:()=>import('../view/backIndex.vue'),
        meta: { requiresAdmin: true },
        children:[
            {
                path:'users',
                name:'back-users',
                component:()=>import('../components/Back-coimponents/backUsers.vue'),
                meta: { requiresAdmin: true },
            },
            {
                path:'products',
                name:'back-products',
                component:()=>import('../components/Back-coimponents/backProducts.vue'),
                meta: { requiresAdmin: true },
            },
            {
                path:'orders',
                name:'back-orders',
                component:()=>import('../components/Back-coimponents/backOrders.vue'),
                meta: { requiresAdmin: true },
            }
        ]
    },
    {
        path:'/robot',
        name:'robot',
        component:()=>import('../view/robot.vue'),
    },
    {
        path:'/profile',
        name:'name',
        component:()=>import('../view/profileView.vue'),
        children:[
        {
            path:'info',
            name:'profile-info',
            component:()=>import('../components/Profile-componment/profile-index.vue')
        },
        {
            path:'mall',
            name:'profile-mall',
            component:()=>import('../components/Profile-componment/Mall.vue')
        },
        {
            path:'order',
            name:'profile-order',
            component:()=>import('../components/Profile-componment/Order.vue')
        },
        {
            path:'pets',
            name:'profile-pets',
            component:()=>import('../components/Profile-componment/Pets.vue')
        },
        {
            path:'settings',
            name:'profile-settings',
            component:()=>import('../components/Profile-componment/Settings.vue')
        }
]
    } 
]

const router = createRouter({
    history: createWebHashHistory(),
    routes,
})

router.beforeEach((to, from, next) => {
    const isAuthenticated = store.getters['user/isLoggedIn'];
    const isAdmin = store.getters['user/isAdmin'];
    
    if (to.meta.requiresAuth && !isAuthenticated) {
      next('/');
    } else if (to.meta.requiresAdmin) {
      if (!isAuthenticated) {
        // 未登录用户尝试访问管理页面
        ElMessage.error('请先登录');
        next('/');
      } else if (!isAdmin) {
        // 已登录但非管理员用户尝试访问管理页面
        ElMessage.error('无权限访问');
        next('/');
      } else {
        // 管理员用户，允许访问
        next();
      }
    } else {
      next();
    }
  });
  

export default router;